package com.gitee.kamismile.stoneComEx.common.component.servlet;

import com.gitee.kamismile.stoneComEx.util.ThreadLocalRequestUtil;
import com.gitee.kamismile.stone.commmon.base.ResultVO;
import com.gitee.kamismile.stoneComEx.common.component.support.BaseController;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.util.StreamUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.async.WebAsyncTask;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.Callable;

public class SimpleServletController extends BaseController {
    protected final Logger logger =LoggerFactory.getLogger(getClass());
    private int asyncOverTime =	Optional
            .ofNullable(System.getProperty("com.gitee.kamismile.stoneComEx.servlet.asyncOverTime"))
            .map(Integer::parseInt)
            .orElseGet(() ->60 * 1000) ;                    //异步请求超时时间


    public Map<String, String> getRequestMap() throws IOException {
        return getRequestMap(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
    }


    public Map<String, String> getRequestMap(HttpServletRequest request) throws IOException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, String> map = new HashMap<String, String>();
        Iterator<String> it = parameterMap.keySet().iterator();
        while (it.hasNext()) {
            String objs = (String) it.next();
            String[] obj = (String[]) parameterMap.get(objs);
            map.put(objs, StringUtils.join(obj, ","));
        }
        ServletInputStream io = request.getInputStream();
        if(Objects.nonNull(io)){
            map.put("requestBody", StreamUtils.copyToString(io, Charset.forName("UTF-8")));
        }

        return map;
    }

    protected WebAsyncTask<ResultVO<String>> failureWebAsyncTask(String message) throws Exception {
        return webAsyncTaskTransfer("-1", message, null);
    }

    protected <T> WebAsyncTask<ResultVO<T>> successfulWebAsyncTask(T result) throws Exception {
        return webAsyncTaskTransfer("0", "操作成功", result);
    }

    public <T> WebAsyncTask<ResultVO<T>> webAsyncTaskTransfer(ResultVO<T> resultVO) throws Exception {
        ResultVO<T> vo = getResultVO(resultVO.getCode(), resultVO.getMessage(), resultVO.getData());
        return webAsyncTaskObj(vo);
    }

    public <T> WebAsyncTask<ResultVO<T>> webAsyncTaskTransfer(String code, String msg, T obj) throws Exception {
        ResultVO vo = getResultVO(code, msg, obj);
        return webAsyncTaskObj(vo);
    }

    public <T> WebAsyncTask webAsyncTaskCallBackTransfer(String code, String msg, T obj, String callback) throws Exception {
        ResultVO vo = getResultVO(code, msg, obj);
        return webAsyncTaskCallBackObj(vo, callback);
    }

    public <T> WebAsyncTask webAsyncTaskCallBackObj(T obj, String callback) throws Exception {
        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(obj);
//        mappingJacksonValue.setJsonpFunction(callback);
        return new WebAsyncTask(asyncOverTime, new Callable<MappingJacksonValue>() {
            @Override
            public MappingJacksonValue call() throws Exception {
                return mappingJacksonValue;
            }
        });
    }

    public <T> WebAsyncTask webAsyncTaskObj(T obj) throws Exception {
        return new WebAsyncTask(asyncOverTime, new Callable<T>() {
            @Override
            public T call() throws Exception {
                return obj;
            }
        });
    }


}

